package com.jnevision.deptcollect.controller;

import java.time.YearMonth;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jnevision.deptcollect.model.DeptCollect;
import com.jnevision.deptcollect.service.DeptCollectServiceImpl;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gavin
 * @since 2019-08-04
 */

@RestController
@RequestMapping("/deptcollects")
public class DeptCollectController extends ApiController {
    @Autowired
    private DeptCollectServiceImpl deptCollectServiceImpl;

    @GetMapping("/year")
    public R<List<DeptCollect>> get(String year, int deptId, boolean isInsurance) {
        List<DeptCollect> deptList = this.deptCollectServiceImpl.list(new QueryWrapper<DeptCollect>()
            .eq(deptId > 0, "dept_id", deptId).like("cycle", year).eq("is_insurance", isInsurance).orderByAsc("cycle"));

        Map<String, DeptCollect> dcMap = Maps.newLinkedHashMap();

        for (DeptCollect dc : deptList) {
            dcMap.put(dc.getCycle(), dc);
        }

        List<DeptCollect> retDeptList = Lists.newArrayList();

        for (int i = 1; i < 13; i++) {
            String yearMonth = YearMonth.of(Integer.parseInt(year), i).toString();

            if (!dcMap.containsKey(yearMonth)) {
                DeptCollect dc = new DeptCollect();

                dc.setCycle(yearMonth);
                dc.setSalary("0");
                dc.setPeopleNum(0);

                retDeptList.add(dc);
            } else {
                retDeptList.add(dcMap.get(yearMonth));
            }
        }

        return this.success(retDeptList);
    }
}
